# coding=utf-8
from django.db.models.query_utils import Q
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from trp.models import *
from utils.JsonResponse import *
from django.shortcuts import render_to_response
import datetime
from django.core.exceptions import ObjectDoesNotExist
import json
from django.http.response import HttpResponse
from utils.decorators import *
import time
from django.db.models import Min,Max,Sum 
from website.settings import LOGGER as logger
from django.db import transaction

@login_required
def main(request):
    account = request.user.account
    if account.is_admin():
        return algorithm_response(request,'trp/algorithm_admin.html',{})    
    else:
        return JsonResponseBadrequest({"message":str("权限不足")})

def algorithm_response(request,html,dic):
    return render_to_response(html, dict({'user' : request.user, 'page' : 'algorithm'},**dic))

@login_required_ajax
def get_list(request):
    try:
        account = request.user.account
        if not account.is_admin():
            raise Exception("权限不足")
        params = json.loads(request.body)
        search_text = params.get("search_text", "")
        pageSize = int(params.get("pageSize", 30))
        pageNo = int(params.get("pageNo", 1))
        status=params.get("status")
        passed=params.get("passed")
        args = []
        if search_text:
            args.append(Q(name__icontains=search_text))
        if status!=None and status!="":
            status=int(status)
            args.append(Q(status=status))
        if passed!=None and passed!="":
            passed=int(passed)
            args.append(Q(passed=passed))
        list = Algorithm.objects.filter(*args).order_by("-id").distinct()
        paginator = Paginator(list, pageSize)
        try:
            pageObj = paginator.page(pageNo)
        except PageNotAnInteger:
            pageObj = paginator.page(1)
        except EmptyPage:
            pageObj = paginator.page(paginator.num_pages)
            
        result={}
        datalist=[]
        for obj in pageObj.object_list:
            data={}
            data["id"]=obj.id
            data["name"]=obj.name
            data["status"]=obj.status
            data["time"]=obj.last_update
            data["passed"]=int(obj.passed)
            datalist.append(data)
        result['bodyData'] = datalist
        result["pageNo"] = pageNo
        result["pageSize"] = pageSize
        result["totalCount"] = paginator.count
    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({'message':str(e)})    
    return JsonResponse(result)    
    
        

@login_required_ajax
@transaction.commit_manually
def create(request):
    try:
        account = request.user.account
        if not account.is_admin():
            raise Exception("权限不足")
        data=json.loads(request.body)
        name = data.get("name","")
        xml_format=data.get("xml_format","")
        code = data.get("code","")
        status=data.get("status",0)
        passed=data.get("passed")
        alg=Algorithm()
        alg.name=name
        alg.xml_format=xml_format
        alg.code=code
        alg.status=status
        if passed:
            alg.passed=int(passed)
        alg.save()
        
        operation_log=OperationLog()
        operation_log.operation="新建"
        operation_log.object="算法"
        operation_log.user=request.user
        operation_log.details="算法名称:"+name.encode("utf-8")      
        operation_log.object_id=alg.id 
        operation_log.save()
    except Exception,e:
        transaction.rollback()
        logger.exception(e)
        return JsonResponseBadrequest({'message':str(e)})
    else:
        transaction.commit()
    return JsonResponse({})
    
@login_required_ajax
@transaction.commit_manually
def update(request):    
    try:
        account = request.user.account
        if not account.is_admin():
            raise Exception("权限不足")
        data=json.loads(request.body)
        alg_id=int(data.get("id",-1))
        name = data.get("name","")
        xml_format=data.get("xml_format","")
        code = data.get("code","")
        status=data.get("status",0)
        passed=data.get("passed")
        
        alg=Algorithm.objects.get(pk=alg_id)
        alg.name=name
        alg.xml_format=xml_format
        alg.code=code
        alg.status=status
        if passed!=None and passed!="":
            alg.passed=int(passed)            
        alg.save()
        
        operation_log=OperationLog()
        operation_log.operation="修改"
        operation_log.object="算法"
        operation_log.user=request.user
        operation_log.details="算法名称:"+name.encode("utf-8")      
        operation_log.object_id=alg_id 
        operation_log.save()
    except Exception,e:
        transaction.rollback()
        logger.exception(e)
        return JsonResponseBadrequest({'message':str(e)})
    else:
        transaction.commit()
    return JsonResponse({})        

@login_required_ajax
@transaction.commit_manually
def delete(request):    
    try:
        account = request.user.account
        if not account.is_admin():
            raise Exception("权限不足")
        data=json.loads(request.body)
        alg_id=int(data.get("id",-1))
        alg=Algorithm.objects.get(pk=alg_id)
        name=alg.name
        if alg.status!=0:
            raise Exception("算法删除失败，请查看其状态")
        alg.delete()
        operation_log=OperationLog()
        operation_log.operation="删除"
        operation_log.object="算法"
        operation_log.user=request.user
        operation_log.details="算法名称:"+name.encode("utf-8")      
        operation_log.object_id=alg_id 
        operation_log.save()
    except Exception,e:
        transaction.rollback()
        logger.exception(e)
        return JsonResponseBadrequest({'message':str(e)})
    else:
        transaction.commit()
    return JsonResponse({})  

@login_required_ajax
def get(request):
    result={}    
    try:
        account = request.user.account
        if not account.is_admin():
            raise Exception("权限不足")
        data=json.loads(request.body)
        alg_id=int(data.get("id",-1))
        alg=Algorithm.objects.get(pk=alg_id)
        result["name"]=alg.name
        result["xml_format"]=alg.xml_format
        result["code"]=alg.code
        result["status"]=alg.status
        result["passed"]=int(alg.passed)
    except Exception,e:
        return JsonResponseBadrequest({'message':str(e)})
    return JsonResponse(result) 

@login_required_ajax
@transaction.commit_manually
def change_status(request):
     try:
        account = request.user.account
        if not account.is_admin():
            raise Exception("权限不足")
        data=json.loads(request.body)
        alg_id=int(data.get("id",-1))
        alg=Algorithm.objects.get(pk=alg_id)
        status=alg.status
        if status==0:
            if not alg.passed:
                raise Exception("算法未通过测试，不予以发布")
            alg.status=1            
            details="发布"
        elif status==1:
            alg.status=2
            details="废弃"
        else:
            raise Exception("已废弃的算法不能进行状态切换")
        alg.save()
        operation_log=OperationLog()
        operation_log.operation="切换状态"
        operation_log.object="算法"
        operation_log.user=request.user
        operation_log.details= "算法名称:"+alg.name.encode("utf-8")+",状态:"+details     
        operation_log.object_id=alg_id 
        operation_log.save()
     except Exception,e:
        transaction.rollback()
        return JsonResponseBadrequest({'message':str(e)})
     else:
         transaction.commit()
     return JsonResponse({}) 
 
def copy_that(request):
    result={}
    try:
        account = request.user.account
        if not account.is_admin():
            raise Exception("权限不足")
        data=json.loads(request.body)
        alg_id=int(data.get("id",-1))
        alg=Algorithm.objects.get(pk=alg_id)
        result["name"]=alg.name.encode("utf-8")+"-副本"
        result["xml_format"]=alg.xml_format
        result["code"]=alg.code
        result["status"]=0      
        result["passed"]=int(alg.passed)
    except Exception,e:
        return JsonResponseBadrequest({'message':str(e)})
    return JsonResponse(result) 
     
def get_release(request):
    params = json.loads(request.body)
    search_text = params.get("search_text", "")   
    pageSize = int(params.get("pageSize", 30))
    pageNo = int(params.get("pageNo", 1))
    args = []
    if search_text:
        args.append(Q(name__icontains=search_text))
    list = Algorithm.objects.filter(*args,status=1).order_by("-id").distinct()
    paginator = Paginator(list, pageSize)
    try:
        pageObj = paginator.page(pageNo)
    except PageNotAnInteger:
        pageObj = paginator.page(1)
    except EmptyPage:
        pageObj = paginator.page(paginator.num_pages)
    datalist=[]
    for obj in pageObj.object_list:
        data={}
        data["id"]=obj.id
        data["name"]=obj.name        
        data["time"]=obj.last_update
        data["code"]=obj.code
        data["xml_format"]=obj.xml_format
        datalist.append(data)
    result={}
    result['bodyData'] = datalist
    result["pageNo"] = pageNo
    result["pageSize"] = pageSize
    result["totalCount"] = paginator.count
    return JsonResponse(result)    
         
        
    